<template>
  <div class="fty-box">
    <!-- 标题 -->
    <PageTitle>
      {{ $t('menu.M_10680202') }}
    </PageTitle>
    <el-card
      class="fty-card"
      shadow="never"
      :body-style="{ padding: '0px' }"
      :page-size="pageSize"
      :total="rows"
      :current-page="pageNo"
      @current-change="currentChangeHandle"
    >
    <div class="search-box">

      <el-form class="p-4" inline :model="dataForm">
        <!--        TODO 多条件输入框 -->
        <!--        <el-form-item>
          <el-input
            v-model="dataForm.condition"
            maxlength="100"
            style="width: 270px"
            :placeholder="$t('operator.condition')"
            clearable
            @blur="() => (dataForm.condition = dataForm.condition.trim())"
            @keyup.enter.native="getDataList((pageNo = 1))"
          />
        </el-form-item>-->
        <el-form-item>
          <el-input
            v-model="dataForm.operatorName"
            :placeholder="$t('operator.name')"
            clearable
            @blur="() => (dataForm.operatorName = dataForm.operatorName.trim())"
            @keyup.enter.native="getDataList((pageNo = 1))"
          />
        </el-form-item>
        <el-form-item v-show="showFormItem('EMAIL')">
          <el-input
            v-model="dataForm.email"
            @blur="() => (dataForm.email = dataForm.email.trim())"
            :placeholder="$t('operator.email')"
            clearable
          />
        </el-form-item>
        <!--        <el-form-item v-show="showFormItem('EMAIL')">
          <el-checkbox v-model="dataForm.includeSubAccounts" :disabled="this.includeSubAccountsVisible" :true-label="1"
                       :false-label="0"  border size="small">{{ $t('operator.include_sub_accounts') }}</el-checkbox>
        </el-form-item>-->
        <el-form-item v-show="showFormItem('LEVEL_CODE')">
          <el-select
            v-model="dataForm.levelCode"
            clearable
            :placeholder="$t('operator.level')"
          >
            <el-option
              v-for="item in levelList"
              :key="item.levelCode"
              :value="item.levelCode"
              :label="item.levelName"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="showFormItem('LOCK_STATUS')">
          <el-select
            v-model="dataForm.operatorStatus"
            clearable
            :placeholder="$t('operator.status')"
          >
            <el-option
              v-for="item in statusMap"
              :key="item.value"
              :value="item.value"
              :label="$t(item.label)"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="showFormItem('REGISTER_DATE')">
          <el-date-picker
            v-model="registerTime"
            type="daterange"
            value-format="x"
            :start-placeholder="$t('operator.register_date')"
            :end-placeholder="$t('operator.register_date')"
            style="width: 300px"
          />
        </el-form-item>
        <el-form-item v-show="showFormItem('LINKMAN')">
          <el-input
            v-model="dataForm.linkman"
            @blur="() => (dataForm.linkman = dataForm.linkman.trim())"
            :placeholder="$t('operator.linkman')"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="w-8"
            @click="getDataList((pageNo = 1))"
          >
            <svg-icon icon-class="search" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="isAuth('10680202.MANAGE')"
            type="primary"
            class="w-8"
            @click="createOperator"
          >
            <svg-icon icon-class="plus" />
          </el-button>
        </el-form-item>

        <!-- <el-form-item>
          <el-button
            v-if="isAuth('10680202.MANAGE')"
            type="primary"
            class="w-8"
            @click="createLevelEmail"
          >
            <svg-icon icon-class="outlined-mail" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="w-8"
            @click="exportOperator"
          >
            <svg-icon icon-class="download" /> -->
            <!--            <svg-icon icon-class="email" class="text-lg" />-->
          <!-- </el-button>
        </el-form-item> -->
        <el-form-item style="float: right">
          <el-button
            style="border: none"
            type="primary"
            class="p-2"
            size="medium"
          >
            <table-column-filter
              :list="settingList"
              :default-setting="defaultSettings"
              v-model:settings="settings"
              domain="operator.table"
            />
          </el-button>
        </el-form-item>
      </el-form>
    </div>

      <el-table v-loading="dataListLoading" :data="dataList" stripe>
        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          :label="$t('operator.name')"
        >
          <template v-slot="scope">
            <div class="cursor-pointer" @click="showDetailHandle(scope.row)">
              {{ scope.row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('LINKMAN')"
          key="linkman"
          prop="linkman"
          header-align="center"
          align="center"
          min-width="100"
          :label="$t('operator.linkman')"
        />
        <el-table-column
          v-if="showHeader('LOCK_STATUS')"
          key="status"
          prop="status"
          header-align="center"
          align="center"
          min-width="100"
          :label="$t('operator.status')"
        >
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === 0" size="small" type="info">
              {{ $t('operator.lock_status_list[0].label') }}
            </el-tag>
            <el-tag v-if="scope.row.status === 1" size="small">
              {{ $t('operator.lock_status_list[1].label') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('COUNTRY')"
          key="countryCode"
          prop="countryCode"
          header-align="center"
          align="center"
          :label="$t('operator.country')"
        >
          <template v-slot="scope">
            {{ $t('country_or_region.' + scope.row.countryCode) }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="showHeader('CRETIME')"
          key="creTime"
          prop="creTime"
          header-align="center"
          align="center"
          :label="$t('operator.register_date')"
        >
          <template v-slot="scope">
            <div :title="timeFilter(scope.row.creTime)">
              {{ dateFilter(scope.row.creTime) }}
              {{ scope.row.creTime ? '' : '-' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="levelCode"
          header-align="center"
          align="center"
          width="200px"
          :label="$t('operator.level')"
        >
          <template v-slot="scope">
            <el-tooltip
              v-if="scope.row.levelName && scope.row.levelName.length > 12"
              class="item"
              effect="dark"
              :content="
                $t('system_menu.level_name') + ': ' + scope.row.levelName
              "
              placement="top"
            >
              <el-tag size="small">
                {{
                  expirationHandler(
                    scope.row.levelName,
                    scope.row.levelExpireTime
                  )
                }}
              </el-tag>
            </el-tooltip>
            <el-tag v-if="!scope.row.levelName || scope.row.levelName.length <= 12" size="small">
              {{
                expirationHandler(
                  scope.row.levelName,
                  scope.row.levelExpireTime
                )
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          :label="$t('common.operate')"
          width="100px"
        >
          <template v-slot="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="$t('common.detail')"
              placement="top"
            >
              <el-button
                type="text"
                style="color: #8c939d"
                @click="showDetailHandle(scope.row)"
              >
              <svg-icon icon-class="outlined-eye" />
            </el-button>
            </el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              :content="
                scope.row.status === 0
                  ? $t('operator.unlock')
                  : $t('operator.lock')
              "
              placement="top"
            >
              <el-button
                v-if="scope.row.status === 1 && isAuth('10680202.MANAGE')"
                type="text"
                @click="lockHandle(scope.row)"
              >
              <svg-icon icon-class="Lock" />
            </el-button>
              <el-button
                v-if="scope.row.status !== 1 && isAuth('10680202.MANAGE')"
                type="text"
                @click="unlockHandle(scope.row)"
              >
              <svg-icon icon-class="Unlock" />
            </el-button>
            </el-tooltip>
            <el-tooltip
              v-if="isAuth('10680202.MANAGE')"
              class="item"
              effect="dark"
              :content="$t('common.deleteBtn')"
              placement="top"
            >
              <el-button
                v-if="
                  (scope.row.status === 1 || scope.row.status === 0) &&
                    isAuth('10680202.MANAGE')
                "
                type="text"
                style="color: #f56c6c"
                @click="deleteHandle(scope.row)"
              >
              <svg-icon icon-class="Delete" />
            </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <business
      v-if="addBusinessVisible"
      ref="business"
      @refreshDataList="getDataList"
      @close="addBusinessVisible = false"
    />
    <change-level
      v-if="changeLevelVisible"
      ref="changeLevel"
      @refreshDataList="getDataList"
      @close="changeLevelVisible = false"
    />
    <add-operator
      v-model="addOperatorVisible"
      ref="addOperator"
      @refreshDataList="getDataList"
      @close="addOperatorVisible = false"
    />
    <permissions
      v-if="permissionsVisible"
      ref="permissions"
      @refreshDataList="getDataList"
      @close="permissions = false"
    />
    <resetpw-operator
      v-if="resetpwOperatorVisible"
      ref="resetpwOperator"
      @refreshDataList="getDataList"
      @close="resetpwOperatorVisible = false"
    />
    <bind-operator
      v-if="addLevelEmailVisible"
      ref="addLevelEmail"
      @close="addLevelEmailVisible = false"
    />
  </div>
</template>

<script>
import { timeFilter, dateFilter } from '@/filters/index'
import TableColumnFilter from '@/components/page-setting/table-column-filter'
import PageTitle from '@/components/PageTitle/index.vue'

import { formatDate } from '@/utils/formatDate'
import { formatCountry } from '@/utils/formatCountry'
import {
  operatorList,
  deleteOperator,
  unlockOperator,
  lockOperator
} from '@/api/operator'
import ResetpwOperator from './components/resetpw-operator'
import Business from './components/add-business'
import ChangeLevel from './components/change-level'
import AddOperator from './components/add-operator'
import Permissions from './components/permissions'
import BindOperator from './components/expired-level-email'
import { getToken } from '@/utils/auth'
import { getSystemMenuList } from '@/api/system-menu'
import { isAuth } from "@/utils";

export default {
  name: 'Operator',
  components: {
    Business,
    ChangeLevel,
    AddOperator,
    Permissions,
    ResetpwOperator,
    BindOperator,
    TableColumnFilter,
    PageTitle
  },
  data() {
    return {
      statusMap:[{
        label: 'operator.locked',
        value: 0,
      },
      {
        label: 'operator.normal',
        value: 1,
      },
    ],
      dataForm: {
        email: '',
        linkman: '',
        includeSubAccounts: 1,
        name: '',
        condition: '',
        operatorStatus: null,
        levelCode: null,
        validityPeriodType: null
      },
      settings: {
        conditions: [],
        columns: []
      },
      registerTime: [],
      operatorDetailVisible: false,
      includeSubAccountsVisible: true,
      addBusinessVisible: false,
      changeLevelVisible: false,
      addOperatorVisible: false,
      addLevelEmailVisible: false,
      updateMapVisible: false,
      permissionsVisible: false,
      resetpwOperatorVisible: false,
      dataList: [],
      pageNo: 1,
      pageSize: 10,
      rows: 0,
      dataListLoading: false,
      orderListLoading: false,
      lockManageLoading: false,
      agreementShowVisible: false,
      curOperator: {},
      operatorLeverList: [],
      levelList: []
    }
  },
  computed: {
    settingList() {
      return {
        conditions: [
          {
            title: this.$t('operator.status'),
            code: 'LOCK_STATUS'
          },
          {
            title: this.$t('operator.level'),
            code: 'LEVEL_CODE'
          },
          {
            title: this.$t('operator.email'),
            code: 'EMAIL'
          },
          {
            title: this.$t('operator.register_date'),
            code: 'REGISTER_DATE'
          },
          {
            title: this.$t('operator.linkman'),
            code: 'LINKMAN'
          }
        ],
        columns: [
          {
            title: this.$t('operator.linkman'),
            code: 'LINKMAN'
          },
          {
            title: this.$t('operator.status'),
            code: 'LOCK_STATUS'
          },
          {
            title: this.$t('operator.country'),
            code: 'COUNTRY'
          },
          {
            title: this.$t('operator.register_date'),
            code: 'CRETIME'
          }
        ]
      }
    },

    defaultSettings() {
      return {
        conditions: ['EMAIL'],
        columns: [
          'LINKMAN',
          // this.$t('common.online'),
        ]
      }
    }
  },
  mounted() {
    this.$store.commit('app/ADD_KEEP_ALIVE_LIST', 'Operator')
    this.init()
  },
  activated() {
    this.getDataList()
  },
  beforeRouteLeave(to, from, next) {
    const allTooltips = document.querySelectorAll('.el-tooltip__popper')
    console.log(allTooltips)
    if (allTooltips.length) {
      Array.from(allTooltips).map((node) => document.body.removeChild(node))
    }
    if (to.name !== 'operator-Info') {
      this.$store.commit('app/REMOVE_KEEP_ALIVE_LIST', 'Operator')
    }
    next()
  },
  methods: {
    isAuth,
    timeFilter,
    dateFilter,
    getLevelInfo() {
      const params = {
        characterCode: '',
        levelCode: '',
        pageNo: 1,
        pageSize: 100
      }
      getSystemMenuList(params)
        .then((res) => {
          this.levelList = res.data
        })
        .catch((e) => {
          this.$confirmError(e)
        })
    },
    async init() {
      this.registerTime = []
      await this.getDataList()
      await this.getLevelInfo()
      await this.getOperatorLevelLsit()
    },
    showHeader(label) {
      var list = this.settings['columns']
      return list ? list.includes(label) : false
    },
    showFormItem(label) {
      var list = this.settings['conditions']
      return list ? list.includes(label) : false
    },
    reset(operatorId, operatorType) {
      this.resetpwOperatorVisible = true
      this.$nextTick(() => {
        this.$refs.resetpwOperator.init(operatorId, operatorType)
      })
    },
    exportOperator() {
      this.$confirm(
        this.$t('operator.export_operator_info_confirm'),
        this.$t('operator.export_operator_info'),
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          window.location.href =
            process.env.VUE_APP_BASE_API +
            '/online/management/admin/operator/export?WEB-TOKEN=' +
            getToken() +
            '&timezone=' +
            Intl.DateTimeFormat().resolvedOptions().timeZone +
            '&pageNo=1&pageSize=10&operatorType=1' +
            '&operatorName=' +
            this.dataForm.operatorName
        })
        .catch(() => {})
    },
    currentOperator(row) {
      this.curOperator = row
    },
    // 获取数据列表
    getDataList() {
      // this.dataListLoading = true
      var regQryStartTime = null
      var regQryEndTime = null
      if (this.registerTime && this.registerTime.length === 2) {
        regQryStartTime = this.registerTime[0] / 1000
        regQryEndTime = this.registerTime[1] / 1000 + 60 * 60 * 24
      }
      console.log(this.registerTime)
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        operatorName: this.dataForm.operatorName,
        condition: this.dataForm.condition,
        operatorStatus: this.dataForm.operatorStatus,
        includeSubAccounts: this.dataForm.includeSubAccounts,
        levelCode: this.dataForm.levelCode,
        email: this.dataForm.email,
        validityPeriodType: this.dataForm.validityPeriodType,
        operatorType: 'NORMAL',
        linkman: this.dataForm.linkman,
        regQryStartTime: regQryStartTime,
        regQryEndTime: regQryEndTime
      }
      console.log(params)
      operatorList(params)
        .then((data) => {
          this.dataList = data.data
          this.rows = data.rows
          this.dataListLoading = false
        })
        .catch((e) => {
          this.dataListLoading = false
          this.$confirmError(e)
          // this.$message.error(e.message)
          console.log(`err:${JSON.stringify(e)}`)
        })
    },
    deleteHandle(row) {
      this.$confirm(this.$t('operator.deleteConfirm'), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.$confirm(this.$t('operator.deleteConfirm1'), '', {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.$confirm(this.$t('operator.deleteConfirm2'), '', {
            confirmButtonText: this.$t('common.confirm'),
            cancelButtonText: this.$t('common.cancel'),
            type: 'warning'
          }).then(() => {
            deleteOperator(row.operatorId)
              .then((data) => {
                this.$message({
                  type: 'success',
                  message: this.$t('common.success')
                })
                this.getDataList()
              })
              .catch((e) => {
                this.$confirmError(e)
              })
          })
        })
      })
      console.log(row)
    },

    // getOperatorLevelLsit() {
    //   const param = {
    //     characterCode: 'OPERATOR'
    //   }
    //   operatorLevelList(param)
    //     .then((data) => {
    //       this.operatorLevelList = data
    //       console.log(this.operatorLevelList)
    //     })
    //     .catch((e) => {
    //       this.$confirmError(e)
    //     })
    // },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageNo = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val
      this.getDataList()
    },
    showDetailHandle(row) {
      localStorage.setItem('operator-info', JSON.stringify(row))
      this.$router.push({
        path: `/operator/operator-detail/${row.operatorId}`
      })
      // this.operatorDetailVisible = true
      // this.$nextTick(() => {
      //   this.$refs.operatorDetail.init(id)
      // })
    },
    
    addLicenseHandle(row) {
      // this.$router.push(
      //   {
      //     path: `/operator/operator-detail`,
      //     query: {
      //       operatorId: row.operatorId,
      //       operatorType: row.operatorType
      //     }
      //   }
      // )
      this.addBusinessVisible = true
      this.$nextTick(() => {
        this.$refs.business.init(row)
      })
    },
    resetMapHandle(row) {
      this.updateMapVisible = true
      this.$nextTick(() => {
        this.$refs.updateMap.init(row)
      })
    },
    blackListHandle(row) {
      this.permissionsVisible = true
      this.$nextTick(() => {
        this.$refs.permissions.init(row)
      })
    },
    formatDate(cellValue, fmt) {
      cellValue = new Date(cellValue).valueOf()
      return formatDate(cellValue, fmt)
    },
    formatCountry(row, column, cellValue, index) {
      return formatCountry(cellValue)
    },
    expirationHandler(Name, levelExpirationTime) {
      // eslint-disable-next-line no-unused-vars
      if (!Name) {
        Name = '-'
      }
      let levelName = Name
      if (Name.length > 11) {
        levelName = Name.slice(0, 11) + '...'
      }
      // if (levelCode === 'STANDARD_LEVEL') {
      //   levelName = this.$t('operator.level_list[0].label')
      // } else if (levelCode === 'ENTERPRISE_LEVEL') {
      //   levelName = this.$t('operator.level_list[1].label')
      // }
      console.log(levelExpirationTime)
      if (!levelExpirationTime || levelExpirationTime === undefined) {
        return levelName + ' | ' + this.$t('operator.leverExpireForever')
      }
      var date = formatDate(levelExpirationTime, 'YYYY-MM-DD')
      return levelName + ' | ' + date
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      let value = row[column.property]
      if (value != null) {
        if (column.property === 'creTime') {
          value = this.formatDate(row[column.property], 'yyyy-MM-dd')
        }
        if (column.property === 'countryCode') {
          value = formatCountry(row[column.property])
        }
        if (value.length * 13 > column.width) {
          return 'font-size:' + (column.width * 0.95) / value.length + 'px'
        }
      }
      // console.log(rowIndex + ':' + JSON.stringify(row))
      //  console.log(columnIndex + ':' + JSON.stringify(column))
    },
    createOperator() {
      this.addOperatorVisible = true
      this.$nextTick(() => {
        this.$refs.addOperator.init()
      })
    },
    createLevelEmail() {
      this.addLevelEmailVisible = true
      this.$nextTick(() => {
        this.$refs.addLevelEmail.init()
      })
    },
    lockHandle(row, lockStatus) {
      this.$confirm(
        this.$t('operator.lock_operator_tip'),
        '',
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        lockOperator(row.operatorId)
          .then((data) => {
            this.$message({
              message: this.$t('common.success'),
              type: 'success'
            })
            this.getDataList()
          })
          .catch((e) => {
            this.$confirmError(e)
          })
      })
    },
    unlockHandle(row) {
      this.$confirm(
     this.$t('operator.unlock_operator_tip')
        ,
        '',
        {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }
      ).then(() => {
        unlockOperator(row.operatorId)
          .then((data) => {
            this.$message({
              message: this.$t('common.success'),
              type: 'success'
            })
            this.getDataList()
          })
          .catch((e) => {
            this.$confirmError(e)
          })
      })
    },
    checkEmail() {
      if (this.dataForm.email.length > 0) {
        this.dataForm.email = this.dataForm.email.trim()
        if (this.dataForm.email.length > 0) {
          this.includeSubAccountsVisible = false
        } else {
          this.includeSubAccountsVisible = true
          this.dataForm.includeSubAccounts = 0
        }
      } else {
        this.includeSubAccountsVisible = true
        this.dataForm.includeSubAccounts = 0
      }
      console.log(
        'this.includeSubAccountsVisible:' + this.includeSubAccountsVisible
      )
    }
  }
}
</script>
<style lang="scss" scope>
.app-container {
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;

  &--border-none {
    border-radius: 0;
  }
}
</style>
